package com.gule.gl.leetcode.editor;

import java.util.ArrayDeque;
import java.util.HashSet;

/**
 * @Auther: gl
 * @Date: 2020/2/11 23:05
 * @Description:
 */
public class LRUUtil {

    public static class LRU {
        private int cacheSize;
        private ArrayDeque<Integer> deque = new ArrayDeque<>();
        private HashSet<Integer> set = new HashSet<>();

        public LRU(int cacheSize) {
            this.cacheSize = cacheSize;
        }

        public Boolean isFull() {
            return deque.size() == cacheSize;
        }

        /**
         * 处理新增加的add
         *
         * @param pageNum
         */
        private void addNew(int pageNum) {
            if (isFull()) {
                //对位删除
                set.remove(deque.getLast());
                deque.pollLast();
            }
            set.add(pageNum);
            deque.push(pageNum);
        }

        /**
         * 添加的常用方法
         *
         * @param page
         */
        public void accessNewPage(Integer page) {
            if (!set.contains(page)) {
                addNew(page);
            } else if (!page.equals(deque.getFirst())) {
                deque.remove(page);
                deque.push(page);
            }
        }
    }

}
